import packages from '../../package.json'

export default {
    setDocumentTitle(name) {
        const title = packages.title
        if(name) {
            document.title = name + '-' + title
        } else {
            document.title = title
        }
    },
    windowSize(callback){
        window.onresize = function(){
            const width = document.body.clientWidth
            const height =  document.body.clientHeight
            const params = {
                width,
                height
            }
            callback && callback(params)
        }
    },
    isObject(obj) {
        if(!obj) return false
        return Object.prototype.toString.call(obj) === '[object Object]'
    },
    isEmptyObj(obj) {
        if(this.isObject(obj) === false) return false
        return Object.keys(obj).length === 0
    },
    isArray(obj) {
        if(!obj) return false
        return Object.prototype.toString.call(obj) === '[object Array]'
    },
    findFirstChildren(tree) {
        if(!tree) return null
        let node = null, first = tree[0]
        if(first) {
            const child = first.children
            if(child && Array.isArray(child)) {
                if(child.length) {
                    node = this.findFirstChildren(child)
                } else {
                    node = first
                }
            }
        }
        return node
    },
    deepClone(source) {
        let target;
        if(typeof(source) === 'object') {
            target = Array.isArray(source) ? []:{}
            for(let key in source) {
                if(typeof(source[key]) === 'object') {
                    target[key] = this.deepClone(source[key])
                } else {
                    target[key] = source[key]
                }
            }
        } else {
            target = source
        }
        return target
    },
    deepMerge(target) {
        const _self = this
        return function(source) {
            if(!source) return _self.deepClone(target)
            if(Object.prototype.toString.call(target) === '[object Object]' && Object.prototype.toString.call(source) === '[object Object]') {
                for(let k in source) {
                    if(!target[k]) {
                        target[k] = source[k]
                    } else {
                        target[k] = _self.deepMerge(target[k])(source[k])
                    }
                }
            } else if(Object.prototype.toString.call(target) === '[object Array]' && Object.prototype.toString.call(source) === '[object Array]') {
                const temp = source.map((item, index) => {
                    if(target[index]) {
                        item = _self.deepMerge(target[index])(item)
                    }
                    return item
                })
                target = temp
            } else {
                target = source
            }
            return target 
        }
    }
}